package com.hele.sts.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.hele.sts.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hele.sts.pub.Constants;
import com.hele.sts.pub.CxqxUtil;
import com.hele.sts.pub.FileManager;
import com.hele.sts.pub.PrintUtils;
import com.hele.sts.pub.StringUtil;
import com.hele.sts.pub.TiffUtils;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import org.springframework.beans.factory.annotation.Autowired;

public class TifContentAction implements Action {
	private static final Logger logger = LoggerFactory.getLogger(TifContentAction.class);

	private String id;
	private String filePath;
	private String sfdy;
	private String msg;
	private int days;
	private String sourceFileName;
	private String ftpAddress;
	private String localPrint;

	@Autowired
	private XtLogDao xtLogDao;

	@Override
	public String execute() throws Exception {

		ActionContext ctx = ActionContext.getContext();
		Map session = ctx.getSession();
		String userId = (String) session.get("userid");
        String username = (String)session.get("user_name");
		if ((userId == null) || ("".equals(userId))) {
			return "login";
		}
		
		if(filePath!=null){
			String path = ServletActionContext.getServletContext().getRealPath("./");
			// logger.debug("当前路径："+path);
			String strAbsPath = new java.io.File(path).getAbsolutePath();
			printByJava(strAbsPath + File.separator + filePath);
			return "ajax";
		}

		if (StringUtils.isBlank(id)) {
			return "error";
		}
		String[] strs = id.split("_");
		if (strs.length != 4) {
			return "error";
		}
		String nbxh = strs[0], jnmlbh = strs[1], inmlbh = strs[2], djjg = strs[3];
		if (StringUtils.isBlank(nbxh) || StringUtils.isBlank(jnmlbh) || StringUtils.isBlank(inmlbh)) {
			return "error";
		}
		if ("1".equals(sfdy)) {
			logger.debug("dy it");
            xtLogDao.insertLog("业务日志","打印企业档案",userId,username,"成功","用户："+userId+" 打印企业："+nbxh+" 档案信息，卷内目录编号："+jnmlbh+" 件内目录编号:"+inmlbh,this.getClass().getName());
            return dy(userId, nbxh, Integer.valueOf(jnmlbh), Integer.valueOf(inmlbh), days);
		}

		String fileName = ""; // 文件名称，不包括路径
		// 创建当天的日期目录 yyyymmdd的格式
		SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMMdd");
		Date mydate = new Date();
		String dateStr = myFormatter.format(mydate);
		long timeStr = mydate.getTime();
		String path = ServletActionContext.getServletContext().getRealPath("./");
	    logger.debug("当前路径："+path);
		String strAbsPath = new java.io.File(path).getAbsolutePath();
		TifInfo tifInfo = TifDao.getTifInfo(nbxh, jnmlbh, inmlbh);
		if (tifInfo == null || tifInfo.getSourceFileName() == null) {
			msg = "没找到档案文件";
			logger.info(msg);
			return "success";
		}
		sourceFileName = tifInfo.getSourceFileName();
		if("2".equals(tifInfo.getCzbz())){
			sourceFileName = getConvertedFile(sourceFileName);
		}else if("0".equals(tifInfo.getCzbz())){
			msg = "该文件不存在";
			logger.info(msg);
			return "success";
		}
		if (!sourceFileName.endsWith(".tif")) {
			msg = "该文件不是档案文件：" + sourceFileName;
			logger.info(msg);
			sourceFileName = sourceFileName.replace("\\", "\\\\");
			filePath = filePath.replace("\\", "/");
			return "success";
		}

		int pos = sourceFileName.lastIndexOf("\\");// nnnnnnnnnnnn not need get
													// splash replace
		if (pos > 0) {
			fileName = sourceFileName.substring(pos + 1, sourceFileName.length());
		}
		ftpAddress = tifInfo.getIpAddress();
		boolean ret = false;
		logger.debug("ftpAdd:{},sourceFileName:{}", ftpAddress, sourceFileName);
		filePath = "tif" + File.separator + dateStr + File.separator + nbxh + timeStr + fileName;
		try {
			ret = FileManager.getDataFiles(ftpAddress, tifInfo.getFtpuser(), tifInfo.getFtppassword(), sourceFileName,
					strAbsPath + File.separator + filePath);
		} catch (IOException ex) {
			logger.error("ftp下载失败", ex);
			sourceFileName = sourceFileName.replace("\\", "\\\\");
			filePath = filePath.replace("\\", "/");
			msg = "ftp下载失败";
			return "success";
		}
		if (!ret) {
			logger.error("ftp下载失败,未下载到对应的图片");
			msg = "未下载到对应的图片";
			sourceFileName = sourceFileName.replace("\\", "\\\\");
			filePath = filePath.replace("\\", "/");
			return "success";
		}

		// filePath = "tif/" + dateStr + "/" + nbxh + timeStr + fileName;
		logger.debug("filePath:" + filePath);
		// 测试tif有无问题，若有问题，下载转化后图片 20150915
		XtServer server = XtServerDao.load(djjg, null, tifInfo.getServerxh());
		//20160403 不再进行图片质量检查
//		if (Constants.TIF_ERRCHECK_CHECK.equals(server.getErrCheck())) {
//			logger.debug("检查图片质量是否有问题，" + filePath);
//			if (!TiffUtils.isValidTif(strAbsPath + File.separator + filePath)) {
//
//				try {
//					String goodTif = sourceFileName.substring(0, pos + 1) + "new-" + fileName;
//					logger.debug("图片有问题，ftp重新下载：{}", goodTif);
//					ret = FileManager.getDataFiles(ftpAddress, tifInfo.getFtpuser(), tifInfo.getFtppassword(), goodTif,
//							strAbsPath + File.separator + filePath);
//				} catch (IOException ex) {
//					logger.error("ftp重新下载失败", ex);
//					msg = "ftp下载失败";
//					return "success";
//				}
//				if (!ret) {
//					logger.error("ftp重新下载失败,未下载到对应的图片");
//					msg = "未下载到对应的图片";
//					return "success";
//				}
//			}
//		}

		// 测试档案权限是否满足
		if (Constants.TIF_PAGECHECK_CHECK.equals(server.getPageCheck())) {

			List<Qyclyqxb> list = TifDao.searchClyqxList(nbxh, jnmlbh, inmlbh);
			if (!list.isEmpty()) {
				String cxqx = (String) session.get("cxqx");
				List<Integer> ymList = new ArrayList<Integer>();
				for (int i = 0; i < list.size(); i++) {
					Qyclyqxb t = list.get(i);
					if (!CxqxUtil.highCxqx(t.getYqx(), cxqx)) {
						ymList.add(t.getYm());
					}
				}
				if (!ymList.isEmpty()) {
					Integer[] ymArray = ymList.toArray(new Integer[ymList.size()]);
					timeStr = System.currentTimeMillis();
					String destFile = "tif" + File.separator + dateStr + File.separator + nbxh + timeStr + fileName;
					// 处理图片
					// 处理图片
					try {
						TiffUtils.deleteTifPage(strAbsPath + File.separator + filePath, strAbsPath + File.separator
								+ destFile, ymArray);
						filePath = destFile;
						logger.debug("图片权限处理结束："+filePath);
					} catch (IOException ex) {
						logger.error("图片处理失败", ex);
						return "success";
					}
				}
			}
		}

		QUser quser = QUserDao.load(userId);
		//String djid = quser.getDjid();
		addLog(userId, nbxh, quser);
		//201660131 comment it
//		QPrintLog printlog = QPrintLogDao.query(userId, nbxh, djid, Integer.valueOf(jnmlbh), Integer.valueOf(inmlbh));
//		if (printlog != null) {
//			// todo
//			this.sfdy = "1";
//		}
		// sfdy = TifDao.getTifSfdy(nbxh, jnmlbh, inmlbh);
		sourceFileName = sourceFileName.replace("\\", "\\\\");
		filePath = filePath.replace("\\", "/");

        xtLogDao.insertLog("业务日志","查询企业档案",userId,username,"成功","用户："+userId+" 查询企业："+nbxh+" 档案信息，卷内目录编号："+jnmlbh+" 件内目录编号:"+inmlbh,this.getClass().getName());

        return "success";
	}

	private void printByJava(String sourceFileName2) {
		PrintUtils.printTiff(sourceFileName2);
	}

	private String dy(String userId, String nbxh, int jnmlbh, int inmlbh, int days) {
		// QLog qLog = new QLog();
		// qLog.setUserId(userId);
		// qLog.setNbxh(nbxh);
		// QUser qUser= QUserDao.load(userId);
		// qLog.setDjid(qUser.getDjid());
		// qLog.setDyrq(new Date());
		// qLog.setSfdy("1");
		// QLogDao.updateByDy(qLog);'
		QUser qUser = QUserDao.load(userId);
		QPrintLog log = QPrintLogDao.query(userId, nbxh, qUser.getDjid(), jnmlbh, inmlbh);
//		if (log != null) {
//			// todo
//			this.sfdy = "1";
//		} else {
			log = new QPrintLog();
			log.setLogId(StringUtil.createLogId());
			log.setUserId(userId);
			log.setNbxh(nbxh);

			log.setDjid(qUser.getDjid());
			log.setJnmlbh(jnmlbh);
			log.setInmlbh(inmlbh);
			log.setSfdy("1");
			log.setDays(days);
			QPrintLogDao.insert(log);
//		}
		// QPrintLog printlog =
		// QPrintLogDao.query(userId,nbxh,qUser.getDjid(),jnmlbh,inmlbh);

		return "ajax";
	}

	private void addLog(String userId, String nbxh, QUser quser) {
		// TODO Auto-generated method stub
		//20160131 comment
		//QLog qlog = QLogDao.query(userId, nbxh, quser.getDjid());
		//if (qlog != null) {
			// QLog qLog = new QLog();
			// qLog.setCxrq(new Date());
			// QLogDao.updateByCx(qLog);
			// 暂时不更新
			// sfdy = qlog.getSfdy();
		//} else {
			QEkUser bean = QEkUserDao.load(userId);
		//	QEnterQueue qBean = QEnterQueueDao.loadByNbxh(userId, nbxh);
			Qyhznr qyhznr = QyhznrDao.load(nbxh);
			if (qyhznr == null) {
				qyhznr = QyhznrDao.loadBfTj(nbxh);
			}
			if (qyhznr == null) {
				logger.error("保存日志失败,未获取到企业信息");
				return;
			}
			Qyajb qyajb = QyajbDao.load(nbxh);
			// QLog qLog = createrQLog(qBean, quser, bean,qyajb);
			QLog qLog = createrQLog2(qyhznr, quser, bean, qyajb);
			if (!QLogDao.insert(qLog)) {
				logger.error("保存日志失败");
				return;
			}
			// sfdy = quser.get
		//}

	}

	/**
	 * @return the id
	 */
	public String getId() {
		return id;
	}

	/**
	 * @param id
	 *            the id to set
	 */
	public void setId(String id) {
		this.id = id;
	}

	/**
	 * @return the filePath
	 */
	public String getFilePath() {
		return filePath;
	}

	/**
	 * @param filePath
	 *            the filePath to set
	 */
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	QLog createrQLog(QEnterQueue eBean, QUser qUser, QEkUser bean, Qyajb qyajb) {
		QLog log = new QLog();
		logger.debug(qUser.getCxrq() + "." + StringUtil.createLogId() + "." + eBean.getNbxh() + "."
				+ eBean.getQymc().trim() + "." + eBean.getUserId() + "." + qUser.getYhlx());
		logger.debug(qUser.getUserName() + "." + bean.getUserName() + "." + eBean.getZch());

		log.setCxrq(new Date());
		log.setLogId(StringUtil.createLogId());
		log.setNbxh(eBean.getNbxh().trim());
		log.setQymc(eBean.getQymc().trim());
		log.setUserId(eBean.getUserId().trim());
		log.setUserName(qUser.getUserName().trim());
		log.setUserNameEk(bean.getUserName().trim());
		log.setYhlx(qUser.getYhlx().trim());
		log.setZch(eBean.getZch().trim());

		log.setRealName(qUser.getRealName());
		log.setYhsf(qUser.getYhsf());
		log.setBz(qUser.getBz());
		log.setDyfs(qUser.getDyfs());
		// xuning add 20150101
		log.setCxmd(qUser.getCxmd());
		// xuning add 20150113
		log.setDjid(qUser.getDjid());
		int days = qyajb.getJnys();
		log.setDays(days);
		log.setSfdy("0");
		return log;
	}

	QLog createrQLog2(Qyhznr qyhznr, QUser qUser, QEkUser bean, Qyajb qyajb) {
		QLog log = new QLog();
		logger.debug(qUser.getCxrq() + "." + StringUtil.createLogId() + "." + qyhznr.getNbxh() + "."
				+ qyhznr.getQymc().trim() + "." + qUser.getUserId() + "." + qUser.getYhlx());
		logger.debug(qUser.getUserName() + "." + bean.getUserName() + "." + qyhznr.getZch());

		log.setCxrq(new Date());
		log.setLogId(StringUtil.createLogId());
		log.setNbxh(qyhznr.getNbxh().trim());
		log.setQymc(qyhznr.getQymc().trim());
		log.setUserId(qUser.getUserId().trim());
		log.setUserName(qUser.getUserName().trim());
		log.setUserNameEk(bean.getUserName().trim());
		log.setYhlx(qUser.getYhlx().trim());
		log.setZch(qyhznr.getZch());

		log.setRealName(qUser.getRealName());
		log.setYhsf(qUser.getYhsf());
		log.setBz(qUser.getBz());
		log.setDyfs(qUser.getDyfs());
		// xuning add 20150101
		log.setCxmd(qUser.getCxmd());
		// xuning add 20150113
		log.setDjid(qUser.getDjid());
		if (qyajb != null ) {
			int days = qyajb.getJnys();
			log.setDays(days);
		}
		log.setSfdy("0");
		return log;
	}

	/**
	 * @return the msg
	 */
	public String getMsg() {
		return msg;
	}

	/**
	 * @param msg
	 *            the msg to set
	 */
	public void setMsg(String msg) {
		this.msg = msg;
	}

	/**
	 * @return the sfdy
	 */
	public String getSfdy() {
		return sfdy;
	}

	/**
	 * @param sfdy
	 *            the sfdy to set
	 */
	public void setSfdy(String sfdy) {
		this.sfdy = sfdy;
	}

	/**
	 * @return the days
	 */
	public int getDays() {
		return days;
	}

	/**
	 * @param days
	 *            the days to set
	 */
	public void setDays(int days) {
		this.days = days;
	}

	/**
	 * @return the sourceFileName
	 */
	public String getSourceFileName() {
		return sourceFileName;
	}

	/**
	 * @param sourceFileName
	 *            the sourceFileName to set
	 */
	public void setSourceFileName(String sourceFileName) {
		this.sourceFileName = sourceFileName;
	}

	/**
	 * @return the ftpAddress
	 */
	public String getFtpAddress() {
		return ftpAddress;
	}

	/**
	 * @param ftpAddress
	 *            the ftpAddress to set
	 */
	public void setFtpAddress(String ftpAddress) {
		this.ftpAddress = ftpAddress;
	}

	/**
	 * @return the localPrint
	 */
	public String getLocalPrint() {
		return localPrint;
	}

	/**
	 * @param localPrint the localPrint to set
	 */
	public void setLocalPrint(String localPrint) {
		this.localPrint = localPrint;
	}
	
	private String getConvertedFile(String filePath) {
		String a = filePath.substring(0,filePath.lastIndexOf("\\")+1);
		String newFile = "new-"+filePath.substring(filePath.lastIndexOf("\\")+1);
		return a+newFile;
	}

}
